package com.geekai.chat.config;

import java.util.Collections;

import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.geekai.chat.entity.User;
import com.geekai.chat.service.UserService;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final UserService userService;
    private final AdminProperties adminProperties;

    public CustomUserDetailsService(@Lazy UserService userService, AdminProperties adminProperties) {
        this.userService = userService;
        this.adminProperties = adminProperties;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 检查是否是管理员
        if (adminProperties.getUsername().equals(username)) {
            return org.springframework.security.core.userdetails.User.builder()
                    .username(username)
                    .password(adminProperties.getPassword())
                    .authorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN")))
                    .accountExpired(false)
                    .accountLocked(false)
                    .credentialsExpired(false)
                    .disabled(false)
                    .build();
        }

        // 检查是否是普通用户
        User user = userService.getUserByUsername(username);
        if (user != null) {
            return org.springframework.security.core.userdetails.User.builder()
                    .username(username)
                    .password(user.getPassword())
                    .authorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))
                    .accountExpired(false)
                    .accountLocked(false)
                    .credentialsExpired(false)
                    .disabled(user.getStatus() == 0)
                    .build();
        }

        throw new UsernameNotFoundException("User not found: " + username);
    }
}
